//
//  OrderListController.m
//  danpin
//
//  Created by chuangjia on 25/11/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "OrderListController.h"
#import "ScrollTabControl.h"
#import "OrderListView.h"
#import "OrderDetailViewController.h"
#import "ShaiDanVC.h"
#import "AppDelegate.h"
#import "AlipayRequestConfig.h"
@interface OrderListController ()<ScrollTabControlDataSource,OrderDelegate,UIAlertViewDelegate>
{
    
}
@property(nonatomic,strong)ScrollTabControl *scrollTabControl;
@property(nonatomic,strong)NSMutableArray *sectionArray;
@property(nonatomic,strong)NSDictionary *statuDictionary;
@property(nonatomic,strong)NSDictionary *alipayDictionary;
@end

@implementation OrderListController

@synthesize scrollTabControl=_scrollTabControl;
@synthesize sectionArray = _sectionArray;
@synthesize statuDictionary=_statuDictionary;
@synthesize alipayDictionary=_alipayDictionary;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle = @"订单列表";
    if (!_sectionArray) {
        _sectionArray = [[NSMutableArray alloc] init];
    }
    _sectionArray =[NSMutableArray arrayWithObjects:@"未付款",@"进行中",@"已完成",@"所有订单", nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateZhifuStatu) name:@"updateZhifuStatu" object:nil];
    [self.view addSubview:self.scrollTabControl];
    [self.scrollTabControl reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.scrollTabControl.datasource =nil;
    self.scrollTabControl= nil;
    
}

-(void)updateZhifuStatu
{
    if (_scrollTabControl) {
        [_scrollTabControl reloadData];
    }
}
-(ScrollTabControl*)scrollTabControl
{
    if (!_scrollTabControl) {
        _scrollTabControl = [[ScrollTabControl alloc] initWithFrame:CGRectMake(0, hightAuto(65), CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-hightAuto(65))];
        _scrollTabControl.datasource = self;
        _scrollTabControl.backgroundColor = [UIColor redColor];
    }
    return _scrollTabControl;
}

- (CGFloat)ScrollTabControlWidth:(ScrollTabControl *)tabCtrl itemAtIndex:(NSUInteger)index
{
    return CGRectGetWidth(self.view.frame)/4;
}

- (NSInteger)ScrollTabControlMenuCount:(ScrollTabControl *)tabCtrl
{
    return self.sectionArray.count;
}

- (TabMenuItem *)ScrollTabControl:(ScrollTabControl *)tabCtrl itemAtIndex:(NSUInteger)index
{
    TabMenuItem *topItem = [[TabMenuItem alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame)/4, 40)];
    topItem.backgroundColor = [UIColor whiteColor];
    topItem.titleLabel.text =[NSString stringWithFormat:@"%@",[self.sectionArray objectAtIndex:index]];
    return topItem;
}

- (UIView *)ScrollTabControl:(ScrollTabControl *)tabCtrl pageAtIndex:(NSUInteger)index
{
    OrderListView *page = [[OrderListView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tabCtrl.frame), CGRectGetHeight(tabCtrl.frame)-40)];
    page.actionstring =[NSString stringWithFormat:@"%@",[self.sectionArray objectAtIndex:index]];
    __weak typeof (self) wSelf = self;
    [page setCallBack:^(UIView *v, id data, id key, id index) {
        [wSelf cellActionViews:v obj:data key:key indexPath:index];
    }];
    return page;
}
-(void)cellActionViews:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
    NSString *status = (NSString *)key;
    NSDictionary *dict = (NSDictionary *)obj;
    _statuDictionary =[NSMutableDictionary dictionaryWithDictionary:obj];
    if ([status isEqualToString:@"orderDetail"])
    { //去订单详情
        OrderDetailViewController *orderDetail =[[OrderDetailViewController alloc] init];
        orderDetail.out_trade_no = [dict objectForKey:@"out_trade_no"];
        orderDetail.from =@"list";
        [self.navigationController pushViewController:orderDetail animated:YES];
        orderDetail=nil;
        return;
    }else if ([status isEqualToString:@"0"]) { //@"去支付"
        NSDictionary *dictt = [obj objectForKey:@"shop_order"];
        if (dictt && [dictt isKindOfClass:[NSDictionary class]]) {
            
            //*支付数据管理
            NSMutableDictionary *pdict = [NSMutableDictionary dictionary];
            [pdict setValue:[[NSString stringWithFormat:@"%@",[dictt objectForKey:@"out_trade_no"]] replaceNullString] forKey:@"out_trade_no"];
            [pdict setValue:[[NSString stringWithFormat:@"%@",[dictt objectForKey:@"subject"]] replaceNullString] forKey:@"subject"];
            NSDictionary *goods_info =[dictt objectForKey:@"goods_info"];
            NSString *productDescription =[[NSString stringWithFormat:@"%@",[goods_info objectForKey:@"good_intro"]] replaceNullString];
            if (productDescription.length==0) {
                productDescription =[[NSString stringWithFormat:@"%@",[dictt objectForKey:@"subject"]] replaceNullString];
            }
            [pdict setValue:productDescription forKey:@"body"];
            [pdict setValue:[[NSString stringWithFormat:@"%@",[dictt objectForKey:@"total_fee"]] replaceNullString] forKey:@"total_fee"];
            
            [pdict setValue:[[NSString stringWithFormat:@"%@",[dictt objectForKey:@"add_time"]] replaceNullString] forKey:@"add_time"];
            [pdict setValue:[[NSString stringWithFormat:@"%@",[dictt objectForKey:@"encryption"]] replaceNullString] forKey:@"encryption"];
            
            if ([self isZhiFu:pdict]) {
                [self alipay:pdict];
            }
        }
        return;
    }else if ([status isEqualToString:@"4"]||[status isEqualToString:@"6"]) { //@"补关税"
        
        NSDictionary *dict = [obj objectForKey:@"shop_order"];
        id order_tariff =[dict objectForKey:@"order_tariff"];
        if(order_tariff && [order_tariff isKindOfClass:[NSDictionary class]])
        {
            int status = [[order_tariff objectForKey:@"status"] intValue];
            if (status==1) {
                return;
            }
            //*支付数据管理
            NSMutableDictionary *pdict = [NSMutableDictionary dictionary];
            [pdict setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"out_trade_no"]] replaceNullString] forKey:@"out_trade_no"];
            [pdict setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"subject"]] replaceNullString] forKey:@"subject"];
            [pdict setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"body"]] replaceNullString] forKey:@"body"];
            [pdict setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"tariff_fee"]] replaceNullString] forKey:@"total_fee"];
            [pdict setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"add_time"]] replaceNullString] forKey:@"add_time"];
            [pdict setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"encryption"]] replaceNullString] forKey:@"encryption"];
            
            if ([self isZhiFu:pdict]) {
                __weak typeof (self) wSelf = self;
                [OrderApi getUserBalance:nil success:^(AFHTTPRequestOperation *operation, id result) {
                    if (result&&[result isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *resultDist =(NSDictionary*)result;
                        if (resultDist && [resultDist isKindOfClass:[NSDictionary class]]) {
                            NSString *balance =[[NSString stringWithFormat:@"%@",[resultDist objectForKey:@"balance"]] replaceNullString];
                            [wSelf usebalanceWithDict:pdict balance:balance];
                        }
                    }
                } failure:^(NSError *error) {
                     [wSelf alipay:pdict];
                }];
              
            }
        }
        return;
    }else if ([status isEqualToString:@"8"]) { //@"确认收货"
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:[[NSString stringWithFormat:@"%@",[obj objectForKey:@"out_trade_no"]] replaceNullString] forKey:@"out_trade_no"];
        __weak typeof (self) wSelf = self;
        [OrderApi signOrder:dict success:^(AFHTTPRequestOperation *operation, id result) {
            if (result&&[result isKindOfClass:[NSDictionary class]]) {
                NSDictionary *resultDist =(NSDictionary*)result;
                [[ZToastManager ShardInstance] showtoast:[resultDist objectForKey:@"msg"]];
                [wSelf updateZhifuStatu];
            }
        } failure:^(NSError *error) {
            
        }];
        return;
    }else if ([status isEqualToString:@"9"]) { //@"点评晒单"
        id goods_info =[dict objectForKey:@"goods_info"];
        NSMutableDictionary *dict =[NSMutableDictionary dictionary];
        if (goods_info && [goods_info isKindOfClass:[NSDictionary class]]) {
            NSString *title =[[NSString stringWithFormat:@"%@",[goods_info objectForKey:@"good_name"]] replaceNullString];
            [dict setValue:title forKey:@"title"];
        }
        ShaiDanVC *shaidanVC =[[ShaiDanVC alloc] init];
        shaidanVC.type=2;
        shaidanVC.cateDictionary = dict;
        [self.navigationController pushViewController:shaidanVC animated:YES];
        return;
    }
}

//=====================================
//余额补税
-(void)usebalanceWithDict:(NSDictionary*)dict balance:(NSString*)balance
{
    NSString *tempBalance = balance;
    if (tempBalance==nil|| tempBalance.length==0 || [balance floatValue]<=0) {
          [self alipay:dict];
    }else
    {
        self.alipayDictionary =[NSMutableDictionary dictionaryWithDictionary:dict];
        NSString *tem = [NSString stringWithFormat:@"您有可用余额%@，是否使用余额？",tempBalance];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:tem delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"使用余额", nil];
        [alert show];
        alert=nil;
    }
   
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            [self alipay:self.alipayDictionary];
        }
            break;
        case 1: //使用
        {
            __weak typeof (self) wSelf = self;
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setValue:[[NSString stringWithFormat:@"%@",[self.alipayDictionary objectForKey:@"out_trade_no"]] replaceNullString] forKey:@"out_trade_no"];
            [OrderApi balanceTariff:dict success:^(AFHTTPRequestOperation *operation, id result) {
                if (result&&[result isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *resultDist =(NSDictionary*)result;
                    int code = [[resultDist objectForKey:@"code"] intValue];
                    if (code==1) {
                       [wSelf updateZhifuStatu];
                    }else
                    {
                        if (resultDist && [resultDist isKindOfClass:[NSDictionary class]]) {
                            id tariff = [resultDist objectForKey:@"tariff"];
                            if (tariff && [tariff isKindOfClass:[NSDictionary class]]) {
                                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                                [dict setValue:[[NSString stringWithFormat:@"%@",[tariff objectForKey:@"out_trade_no"]] replaceNullString] forKey:@"out_trade_no"];
                                [dict setValue:[[NSString stringWithFormat:@"%@",[tariff objectForKey:@"subject"]] replaceNullString] forKey:@"subject"];
                                [dict setValue:[[NSString stringWithFormat:@"%@",[tariff objectForKey:@"body"]] replaceNullString] forKey:@"good_intro"];
                                [dict setValue:[[NSString stringWithFormat:@"%@",[tariff objectForKey:@"tariff_fee"]] replaceNullString] forKey:@"total_fee"];
                                [wSelf alipay:dict];
                            }
                        }
                    }
                }
            } failure:^(NSError *error) {
                [wSelf alipay:wSelf.alipayDictionary];
            }];
        }
            break;
        default:
            break;
    }
}

//=================================================
// 订单提交成功判断支付信息
//返回值 json
//{
//    'code' => 1,
//    'msg' => '订单保存成功',
//    'add_time' => $add_time,
//    'total_fee' => $total_fee,
//    'out_trade_no' => $param['out_trade_no'],
//    'encryption' => md5($param['out_trade_no'] . $_SESSION['user_id'] . $total_fee . $Keys . $add_time),
//    'md5str' => $param['out_trade_no'] . $_SESSION['user_id'] . $total_fee . $Keys . $add_time,
//}
// key @"chrdwHDHXT12345ssdlh";
//=================================================
-(BOOL)isZhiFu:(NSDictionary*)dictionary
{
    if (dictionary==nil || ![[dictionary allKeys] containsObject:@"out_trade_no"]) {
        return NO;
    }
    //添加订单后支付
    NSString *add_time =[[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"add_time"]] replaceNullString];
    NSString *total_fee =[[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"total_fee"]] replaceNullString];
    NSString *out_trade_no =[[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"out_trade_no"]] replaceNullString];
    NSString *encryption =[[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"encryption"]] replaceNullString];
    NSString *md5str = [NSString stringWithFormat:@"%@%@%@chrdwHDHXT12345ssdlh%@",out_trade_no,[ZShare sharedInstance].getUserId,total_fee,add_time];
    md5str = [ZShare md5:md5str];
    if ([md5str isEqualToString:encryption]) {
        return YES;
    }
    return NO;
}

-(void)alipay:(NSDictionary*)dict
{
    NSString *totalfee =[[NSString stringWithFormat:@"%@",[dict objectForKey:@"total_fee"]] replaceNullString];
    if ([totalfee floatValue]==0) {
        return;
    }
    NSString *tradeNO = [dict objectForKey:@"out_trade_no"]; //订单ID（由商家自行制定）
    NSString *productName = [dict objectForKey:@"subject"]; //商品标题
    NSString *productDescription =[dict objectForKey:@"body"];
    NSString *amount = [dict objectForKey:@"total_fee"];; //商品价格
    AppDelegate *app = [[UIApplication sharedApplication]delegate];
    app.orderDelegate=self;
    __weak typeof (self) wSelf = self;
    [AlipayRequestConfig alipayWithTradeNO:tradeNO productName:productName productDescription:productDescription amount:amount callback:^(NSDictionary *resultDic) {
        [wSelf orderPayOK:resultDic];
    }];
}
-(void)orderPayOK:(id)info
{
    NSDictionary *resultDic =(NSDictionary *)info;
    AppDelegate *app = [[UIApplication sharedApplication]delegate];
    app.orderDelegate=nil;
    NSString *memo = [resultDic objectForKey:@"memo"];
    if (memo.length>0) {
        [[ZToastManager ShardInstance] showtoast:memo];
    }
    
    NSString *resultStatus = [resultDic objectForKey:@"resultStatus"];
    if ([resultStatus isEqualToString:@"9000"]) {
        NSMutableDictionary *dcit =[NSMutableDictionary dictionary];
        [dcit setValue:@"0" forKey:@"rmb"];
        NSString *status =[[NSString stringWithFormat:@"%@",[_statuDictionary objectForKey:@"status"]] replaceNullString];
        if ([status intValue]==0) {
            
        }else if ([status intValue]==6) {
            NSDictionary *dict = [_statuDictionary objectForKey:@"shop_order"];
            NSDictionary *order_tariff =[dict objectForKey:@"order_tariff"];
            [dcit setValue:[[NSString stringWithFormat:@"%@",[order_tariff objectForKey:@"tariff_fee"]] replaceNullString] forKey:@"tariff_fee"];
        }
        [dcit setValue:[ZShare DataTOjsonString:resultDic] forKey:@"return_data"];
        [OrderApi alipayReturnUrl:dcit success:^(AFHTTPRequestOperation *operation, id result) {
            //            NSLog(@"%@",result);
        } failure:^(NSError *error) {
            
        }];
        
        [self updateZhifuStatu];
        
    }else  if ([resultStatus isEqualToString:@"6001"])
    {
        
    }
}

//=======================
//
//=======================
@end
